package com.sky.service.admin.impl;

import com.sky.dto.GoodsSalesDTO;
import com.sky.entity.Orders;
import com.sky.mapper.OrdersMapper;
import com.sky.service.admin.ReportService;
import com.sky.service.admin.WorkspaceService;
import com.sky.vo.BusinessDataVO;
import com.sky.vo.SalesTop10ReportVO;
import com.sky.vo.TurnoverReportVO;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
 * @author wangqi
 * @date 2024/1/8 09:20
 */
@Slf4j
@Service
public class ReportServiceImpl implements ReportService {

    @Autowired
    private OrdersMapper ordersMapper;

    @Autowired
    private WorkspaceService workspaceService;

    /**
     * 统计在指定时间段内每一天的营业额
     *
     * @param begin
     * @param end
     * @return
     */
    @Override
    public TurnoverReportVO getTurnover(LocalDate begin, LocalDate end) {
        //1.定义一个存储指定时间段内的每一天日期时间的集合（横轴的数据）
        ArrayList<LocalDate> dateList = new ArrayList<>();
        dateList.add(begin);
        while (!begin.equals(end)) {
            begin = begin.plusDays(1);
            dateList.add(begin);
        }

        //2.定义一个集合，用来存储每一天的营业额数据
        ArrayList<Double> turnoverList = new ArrayList<>();
        for (LocalDate date : dateList) {
            //每一天指的是从yyyy-MM-dd的00:00:00~yyyy-MM-dd的23:59:59之间的时间
            LocalDateTime beginTime = LocalDateTime.of(date, LocalTime.MIN);
            LocalDateTime endTime = LocalDateTime.of(date, LocalTime.MAX);
            //从orders表中查询从beginTime到endTime时间段已完成订单的营业额
            Map map = new HashMap();
            map.put("status", Orders.COMPLETED);
            map.put("begin", beginTime);
            map.put("end", endTime);
            //查询这时间段内，每一天的营业额
            Double turnover = ordersMapper.turnoverByMap(map);
            turnover = turnover == null ? 0.0 : turnover;
            turnoverList.add(turnover);
        }

        //3.封装返回结果数据
        //把dateList集合转换为以","隔开的字符串
        String dates = StringUtils.join(dateList, ",");
        log.info("日期字符串：" + dates);
        //把turnoverList集合转换为以","隔开的字符串
        String trunovers = StringUtils.join(turnoverList, ",");

        TurnoverReportVO turnoverReportVO = TurnoverReportVO.builder()
                .dateList(dates)
                .turnoverList(trunovers)
                .build();

        return turnoverReportVO;
    }

    @Override
    public SalesTop10ReportVO getSalesTop10(LocalDate begin, LocalDate end) {
        //1.创建开始和结束的时间
        LocalDateTime beginTime = LocalDateTime.of(begin, LocalTime.MIN);
        LocalDateTime endTime = LocalDateTime.of(end, LocalTime.MAX);

        //2.查询orders和order_detail表在指定时间段内的每一个菜品名称和销量
        List<GoodsSalesDTO>  goodsSalesDTOList = ordersMapper.getSalesTop10(beginTime,endTime);

        //3.把上一步的list集合，分解成存储name的集合和存储number的集合
        List<String> nameList = goodsSalesDTOList.stream().map(goodsSalesDTO -> goodsSalesDTO.getName()).collect(Collectors.toList());
        List<Integer> numberList = goodsSalesDTOList.stream().map(goodsSalesDTO -> goodsSalesDTO.getNumber()).collect(Collectors.toList());

        //4.再把nameList和numberList转化为字符串，封装为SalesTop10ReportVO并返回
        String names = StringUtils.join(nameList, ",");
        String numbers = StringUtils.join(numberList, ",");

        SalesTop10ReportVO salesTop10ReportVO = SalesTop10ReportVO.builder()
                .numberList(numbers)
                .nameList(names)
                .build();

        return salesTop10ReportVO;
    }

    /**
     * 下载近30天的运营数据
     * @param response
     */
    @Override
    public void exportBusinessData(HttpServletResponse response) {
        //1.设置获取数据的时间段
        LocalDate beginTime = LocalDate.now().minusDays(30);
        LocalDate endTime = LocalDate.now().minusDays(1);

        //2.获取从beginTime到endTime时间段内的运营数据(近30天的运用数据总览)
        BusinessDataVO businessData = workspaceService.getBusinessData(
                LocalDateTime.of(beginTime, LocalTime.MIN),
                LocalDateTime.of(endTime, LocalTime.MAX)
        );

        //3.把businessData中的数据填充到excel表格中
        try {
            //3.1 以模版文件为基础创建工作簿
            InputStream inputStream = this.getClass().getClassLoader().getResourceAsStream("template/运营数据报表模板.xlsx");
            XSSFWorkbook excel = new XSSFWorkbook(inputStream);

            //3.2 获取工作簿中的Sheet1页里面的1索引的行,1索引的列,给这一个单元格设置日期区间
            XSSFSheet sheet = excel.getSheet("Sheet1");
            sheet.getRow(1).getCell(1).setCellValue(beginTime+"至"+endTime);

            //3.3 获取Sheet1页中的3索引的行
            XSSFRow row = sheet.getRow(3);
            //3.4 获取row这一行索引为2的单元格，设置营业额
            row.getCell(2).setCellValue(businessData.getTurnover());
            //3.5 获取row这一行索引为4的单元格，设置订单完成率
            row.getCell(4).setCellValue(businessData.getOrderCompletionRate());
            //3.6 获取row这一行索引为6的单元格，设置新增用户
            row.getCell(4).setCellValue(businessData.getNewUsers());

            //4.1 获取Sheet1页中的4索引的行
            XSSFRow row1 = sheet.getRow(4);
            //4.2 获取row1这一行索引为2的单元格，设置有效订单
            row1.getCell(2).setCellValue(businessData.getValidOrderCount());
            //4.3 获取row1这一行索引为4的单元格式，设置客单价
            row1.getCell(4).setCellValue(businessData.getUnitPrice());

            //5.在表格中设置近30天每一天的明细数据
            for (int i = 0; i < 30; i++) {
                //获取近30天的每一天
                LocalDate date = beginTime.plusDays(i);
                LocalDateTime begin = LocalDateTime.of(date, LocalTime.MIN);
                LocalDateTime end = LocalDateTime.of(date, LocalTime.MAX);
                //获取每一天营业额
                BusinessDataVO businessData1 = workspaceService.getBusinessData(begin, end);

                //获取excel表格每一天的行
                XSSFRow row2 = sheet.getRow(7 + i);
                row2.getCell(1).setCellValue(date.toString());
                row2.getCell(2).setCellValue(businessData1.getTurnover());
                row2.getCell(3).setCellValue(businessData1.getValidOrderCount());
                row2.getCell(4).setCellValue(businessData1.getOrderCompletionRate());
                row2.getCell(5).setCellValue(businessData1.getUnitPrice());
                row2.getCell(6).setCellValue(businessData1.getNewUsers());
            }

            //6.将表格数据写到文件中，响应给前端
            ServletOutputStream out = response.getOutputStream();
            excel.write(out);

            //7.释放资源
            out.flush();
            out.close();
            excel.close();

        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
}
